//
//  MQNetWorkTools.swift
//  MQWeibo
//
//  Created by 毛强 on 15/12/30.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import AFNetworking

enum MQRequestMethod: String{
    case GET = "GET"
    case POST = "POST"
}

class MQNetWorkTools: AFHTTPSessionManager {
    static let sharedTools:MQNetWorkTools = {
        let instance = MQNetWorkTools()
        instance.responseSerializer.acceptableContentTypes?.insert("text/html")
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    
    typealias MQRequestCallBack = (response:AnyObject?, error: NSError?) -> ()
    
    func request(method: MQRequestMethod? = .GET, urlString: String, parameters: AnyObject?, finished:MQRequestCallBack){
        
        let success = { (dataTasks:NSURLSessionDataTask, responseObject:AnyObject?) -> Void in
            finished(response: responseObject, error: nil)
        }
        
        let failure = {(dataTasks:NSURLSessionDataTask?, error:NSError) ->Void in
            finished(response: nil, error: error)
        }
        
        if method == .GET{
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
}

// MARK: - OAuth 登录获取数据
extension MQNetWorkTools {
    
    /// 请求accessToken
    ///
    /// - parameter code:     授权码
    /// - parameter finished: 请求完成的闭包回调
    func loadAccessToken(code: String, finished:MQRequestCallBack){
        // 请求地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 请求参数
        let params = [
            "client_id": WB_APPKEY,
            "client_secret": WB_SECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WB_REGIRECTURI
        ]
        // 发送请求
        request(.POST, urlString: urlString, parameters: params, finished: finished)
    }
    
    /// 请求个人信息
    ///
    /// - parameter accessToken: <#accessToken description#>
    /// - parameter uid:         <#uid description#>
    func loadUserAccount(accessToken: String, uid: String, finished: MQRequestCallBack){
        // 请求地址
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 请参数
        let params = [
            "access_token": accessToken,
            "uid": uid
        ]
        request(urlString: urlString, parameters: params, finished: finished)
    }
}

